package com.tcs.teg.web.accounts;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.access.annotation.Secured;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.Validator;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.i18n.SessionLocaleResolver;
import org.springframework.web.servlet.support.RequestContext;
import org.springframework.web.util.WebUtils;

import com.tcs.teg.domain.accounts.AccountRegistrationForm;
import com.tcs.teg.service.accounts.IAccountService;

@Controller
public class RegistrationController {
	
	private static final Log logger = LogFactory.getLog(RegistrationController.class);
	
	private IAccountService accountService;
	private Validator validator;
	
	@Autowired
	public RegistrationController(IAccountService accountService, @Qualifier("RegistrationFormValidator") Validator validator) {
		this.accountService = accountService;
		this.validator = validator;
	}
	
	@RequestMapping(value = "/accountRegistrationForm",	method = RequestMethod.GET)
	public void register(Model model, HttpServletRequest request, RequestContext reqContext) {	
		logger.debug("GET EXECUTED");
		logger.debug("getting session locale"+WebUtils.getSessionAttribute(request, SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME));
		logger.debug("gettng locale from request context"+reqContext.getLocale());
		AccountRegistrationForm arf = new AccountRegistrationForm();
		model.addAttribute("accountRegistrationForm",arf);
		logger.debug("GET EXECUTED");
	}
	
	@RequestMapping(value = "/accountRegistrationForm",	method = RequestMethod.POST)
	public String saveRegistrationDetails(AccountRegistrationForm arf, BindingResult bindingResult) {
		logger.debug("In accountRegistrationForm");
		
		validator.validate(arf, bindingResult);
		logger.debug("bindingResult.hasErrors() ..... "+bindingResult.hasErrors());
		if (! bindingResult.hasErrors()) {
			logger.debug("No Errors !!!!!!!!!" ) ;
			
			accountService.saveRegistrationDetails(arf);
			arf.setFormSubmissionStatus(true);
		}
		
		return "accountRegistrationForm";
	}

}
